package com.qlslylq.ad.example.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.menu.ActionMenuItemView;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.Toolbar;

import com.qlslylq.ad.example.R;
import com.qlslylq.ad.sdk.manager.ActivityManager;
import com.qlslylq.ad.sdk.util.Log;
import com.qlslylq.ad.sdk.util.SystemBarTintManager;

import java.io.Serializable;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * created by qlslylq <br/>
 * on 2015 <br/>
 *
 * @Link https://gitee.com/qlslylq
 */
public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {

    /**
     * 上下文
     */
    protected BaseActivity activity;

    /**
     * 公用标题栏
     */
    private Toolbar toolbar;

    /**
     * 返回按钮
     */
    private AppCompatImageButton btn_back;

    /**
     * 标题栏公用标题控件
     */
    private TextView tv_title;

    /**
     * btn_right控件
     */
    private ActionMenuItemView btn_right;

    /**
     * iv_border控件
     */
    private ActionMenuItemView iv_border;

    /**
     * BaseActivity及BaseFragment的内容布局
     */
    protected ViewGroup contentView;

    /**
     * 进度条parent
     */
    private ViewGroup progressBar;

    /**
     * 进度条文本
     */
    private TextView tv_progressbar;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = this;
        pushActivityToStack();
        Log.d(this, "activity");
    }

    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    @SuppressLint("RestrictedApi")
    protected void onResume() {
        super.onResume();
        if (isEmpty(btn_right.getText().toString())) {
            String tag_1 = (String) btn_right.getTag(R.id.tag_key_1);
            Integer tag_2 = (Integer) btn_right.getTag(R.id.tag_key_2);
            if (tag_1 != null) {
                String[] array = tag_1.split(",");
                if (array[0].equals("res")) {
                    btn_right.setIcon(getResources().getDrawable(Integer.parseInt(array[1])));
                } else if (array[0].equals("text")) {
                    btn_right.setIcon(null);
                    btn_right.setText(array[1]);
                }
            }
            if (tag_2 != null) {
                btn_right.setVisibility(tag_2);
            }
        }
        if (isEmpty(iv_border.getText().toString())) {
            String tag_1 = (String) iv_border.getTag(R.id.tag_key_1);
            Integer tag_2 = (Integer) iv_border.getTag(R.id.tag_key_2);
            if (tag_1 != null) {
                String[] array = tag_1.split(",");
                if (array[0].equals("res")) {
                    iv_border.setIcon(getResources().getDrawable(Integer.parseInt(array[1])));
                } else if (array[0].equals("text")) {
                    iv_border.setIcon(null);
                    iv_border.setText(array[1]);
                }
            }
            if (tag_2 != null) {
                iv_border.setVisibility(tag_2);
            }
        }
    }

    /**
     * 设置所有BaseActivity子类的根布局为layout中的common_root.xml布局文件<br/>
     */
    @SuppressWarnings("ResourceType")
    private void setRootView() {
        super.setContentView(R.layout.common_root_fit);
        toolbar = (Toolbar) findViewById(R.id.title_view);
        toolbar.setNavigationIcon(R.drawable.back_white);
        toolbar.setTitle("");
        toolbar.inflateMenu(R.menu.title_right);
        btn_back = (AppCompatImageButton) toolbar.getChildAt(1);
        btn_back.setId(R.id.btn_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        btn_right = (ActionMenuItemView) findViewById(R.id.btn_right);
        iv_border = (ActionMenuItemView) findViewById(R.id.iv_border);
        btn_right.setVisibility(View.GONE);
        iv_border.setVisibility(View.GONE);
        btn_right.setTextColor(getResources().getColorStateList(R.drawable.selector_text_color));
        iv_border.setTextColor(getResources().getColorStateList(R.drawable.selector_text_color));
        progressBar = (ViewGroup) findViewById(R.id.viewgroup_progressbar);
        tv_progressbar = (TextView) progressBar.getChildAt(1);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                finish();
            }
        });
        btn_right.setOnClickListener(this);
        iv_border.setOnClickListener(this);
    }

    /**
     * 获取根节点控件<br/>
     */
    public ViewGroup getRootView() {
        return (ViewGroup) findViewById(R.id.common_root);
    }

    /**
     * 设置BaseActivity子类的内容布局
     */
    public void setContentView(int resource) {
        setRootView();
        ViewGroup commoon_content = (ViewGroup) findViewById(R.id.viewgroup_common_content);
        contentView = (ViewGroup) getLayoutInflater().inflate(resource, null);
        contentView.setId(R.id.contentView);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        commoon_content.addView(contentView, params);
        init();
    }

    /**
     * 查找和添加公有控件，初始化数据及监听<br/>
     */
    private void init() {
        initView();
        initData();
        initListener();
    }

    /**
     * 全屏<br/>
     */
    public void setFullScreen() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 显示标题栏<br/>
     */
    public void showTitleBar() {
        toolbar.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏标题栏<br/>
     */
    public void hideTitleBar() {
        toolbar.setVisibility(View.GONE);
    }

    /**
     * 设置标题栏的背景色<br/>
     */
    public void setTitleBarBackgroundResource(int resid) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(resid);
        toolbar.setBackgroundResource(resid);
    }

    /**
     * 设置标题栏的背景色<br/>
     */
    public void setTitleBarBackgroundColor(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintColor(color);
        toolbar.setBackgroundColor(color);
    }

    public void setTitleBarEnabled(boolean enabled) {
        btn_right.setEnabled(enabled);
        iv_border.setEnabled(enabled);
    }

    /**
     * 设置通知栏背景色<br/>
     */
    public void setImmersionBarColor(int color) {
        SystemBarTintManager tintManager = new SystemBarTintManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintColor(color);
    }

    /*
     * 设置标题栏返回按钮的资源图片
     */
    public void setBackButtonResource(int resid) {
        btn_back.setImageResource(resid);
    }

    /**
     * 重置返回按钮的点击事件<br/>
     */
    public void setBackButtonClickListener(View.OnClickListener onClickListener) {
        btn_back.setOnClickListener(onClickListener);
    }

    /**
     * 显示标题栏的返回按钮
     */
    public void showBackButton() {
        btn_back.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏标题栏的返回按钮
     */
    public void hideBackButton() {
        btn_back.setVisibility(View.GONE);
    }

    /**
     * 设置标题栏的标题
     */
    public void setTitle(String name) {
        tv_title.setText(name);
    }

    /**
     * 设置btn_right的资源图片
     */
    @SuppressLint("RestrictedApi")
    public void setRightButtonResource(int resid) {
        btn_right.setIcon(getResources().getDrawable(resid));
        btn_right.setTag(R.id.tag_key_1, "res," + resid);
    }

    /**
     * 设置btn_right的文本
     */
    @SuppressLint("RestrictedApi")
    public void setRightButtonText(String text) {
        btn_right.setIcon(null);
        btn_right.setText(text);
        btn_right.setTag(R.id.tag_key_1, "text," + text);
    }

    /**
     * 显示btn_right
     */
    public void showRightButton() {
        btn_right.setVisibility(View.VISIBLE);
        btn_right.setTag(R.id.tag_key_2, View.VISIBLE);
    }

    /**
     * 隐藏btn_right
     */
    public void hideRightButton() {
        btn_right.setVisibility(View.GONE);
        btn_right.setTag(R.id.tag_key_2, View.GONE);
    }

    /**
     * 设置iv_border的资源图片
     */
    @SuppressLint("RestrictedApi")
    public void setBorderViewResource(int resid) {
        iv_border.setIcon(getResources().getDrawable(resid));
        iv_border.setTag(R.id.tag_key_1, "res," + resid);
    }

    /**
     * 设置iv_border的文本
     */
    @SuppressLint("RestrictedApi")
    public void setBorderViewText(String text) {
        iv_border.setIcon(null);
        iv_border.setText(text);
        iv_border.setTag(R.id.tag_key_1, "text," + text);
    }

    /**
     * 显示iv_border
     */
    public void showBorderView() {
        iv_border.setVisibility(View.VISIBLE);
        iv_border.setTag(R.id.tag_key_2, View.VISIBLE);
    }

    /**
     * 隐藏iv_border
     */
    public void hideBorderView() {
        iv_border.setVisibility(View.GONE);
        iv_border.setTag(R.id.tag_key_2, View.GONE);
    }

    /**
     * 设置进度栏文本
     */
    public void setProgressBarText(String text) {
        tv_progressbar.setText(text);
    }

    /**
     * 重置进度栏文本
     */
    public void resetProgressBarText() {
        tv_progressbar.setText(getString(R.string.progressbar_text));
    }

    /**
     * 显示进度条及隐藏输入法<br/>
     */
    public void showProgressBar() {
        progressBar.setVisibility(View.VISIBLE);
        hideSoftInput();
    }

    /**
     * 隐藏进度条<br/>
     */
    public void hideProgressBar() {
        progressBar.setVisibility(View.GONE);
    }

    /**
     * 隐藏输入法<br/>
     */
    public void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (getCurrentFocus() != null) {
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 显示长Toast
     */
    public void showToast(String text) {
        if (!isEmpty(text)) {
            Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
            if (toast.getView() != null && toast.getView() instanceof LinearLayout) {
                LinearLayout toastView = (LinearLayout) toast.getView();
                toastView.setBackgroundResource(R.drawable.bg_toast);
                TextView textView = (TextView) toastView.getChildAt(0);
                textView.setPadding(0, 0, 0, 0);
                textView.setText(text);
            }
            toast.show();
        }
    }

    /**
     * 显示短Toast
     */
    public void showShortToast(String text) {
        if (!isEmpty(text)) {
            Toast toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
            if (toast.getView() != null && toast.getView() instanceof LinearLayout) {
                LinearLayout toastView = (LinearLayout) toast.getView();
                toastView.setBackgroundResource(R.drawable.bg_toast);
                TextView textView = (TextView) toastView.getChildAt(0);
                textView.setPadding(0, 0, 0, 0);
                textView.setText(text);
            }
            toast.show();
        }
    }


    /**
     * 查找contentView下的控件<br/>
     */
    public <V extends View> V findView(int id) {
        V currentView = (V) contentView.findViewById(id);
        return currentView;
    }

    /**
     * 查找指定序号的同名id控件<br/>
     * 序号从1开始<br/>
     */
    public <V extends View> V findView(int id, int order) {
        return findView(contentView, id, order, new AtomicInteger(0));
    }

    /**
     * 查找指定序号的同名id控件<br/>
     * 序号从1开始<br/>
     */
    public <V extends View> V findView(ViewGroup rootGroup, int id, int order) {
        return findView(rootGroup, id, order, new AtomicInteger(0));
    }

    /**
     * 实现查找指定序号的同名id控件<br/>
     */
    @SuppressWarnings("unchecked")
    private <V extends View> V findView(ViewGroup rootGroup, int id, int order, AtomicInteger order_num) {
        for (int childIndex = 0, childCount = rootGroup.getChildCount(); childIndex < childCount; childIndex++) {
            View childView = rootGroup.getChildAt(childIndex);
            if (childView.getId() == id) {
                if (order_num.incrementAndGet() == order) {
                    return (V) childView;
                }
            }
            if (childView instanceof ViewGroup) {
                View resultView = findView((ViewGroup) childView, id, order, order_num);
                if (resultView == null) {
                    continue;
                } else {
                    return (V) resultView;
                }
            }
        }
        return null;
    }

    public void startActivity(Class<? extends Activity> destClass) {
        Intent intent = new Intent(this, destClass);
        super.startActivity(intent);
    }

    public void startActivity(Serializable data, Class<? extends Activity> destClass) {
        Intent intent = new Intent(this, destClass);
        intent.putExtra("data", data);
        super.startActivity(intent);
    }

    public void setRefresh(boolean refresh) {
        Intent intent = new Intent();
        intent.putExtra("refresh", refresh);
        setResult(0, intent);
    }

    public boolean hasRefresh(Intent intent) {
        if (intent != null && intent.getBooleanExtra("refresh", false)) {
            return true;
        }
        return false;
    }

    public boolean isEmpty(CharSequence src) {
        return TextUtils.isEmpty(src);
    }

    protected void onDestroy() {
        super.onDestroy();
        System.gc();
    }

    /**
     * 用于控制标题栏及初始化控件<br/>
     */
    protected abstract void initView();


    /**
     * 用于初始化数据<br/>
     */
    protected abstract void initData();


    /**
     * 用于设置事件监听<br/>
     */
    protected abstract void initListener();

    public void onDbSucceed(String method, Object values) {
        showToast(values.toString());
    }

    public void onDbFaild(String method, Object values) {
        showToast(values + "");
        Log.e("db", values);
    }

    public void onNetWorkSucceed(String method, Object values) {
        showToast(values + "");
    }

    public void onNetWorkFaild(String method, Object values) {
        showToast(values + "");
        Log.e("http", values);
    }

    public void onOtherSucceed(String method, Object values) {
        showToast(values + "");
    }

    public void onOtherFaild(String method, Object values) {
        showToast(values + "");
        Log.e("other", values);
    }

    public void onException(String method, Exception e) {
        String error = "网络连接出现异常："
                + "\n    异常运行窗口：" + getClass().getName()
                + "\n    捕获异常函数：" + method
                + "\n    " + e;
        Log.e(error);
        Log.e("error", error);
        showToast(error);
    }

    public void onCancel(String method) {

    }

    public void onClick(View view) {
        showToast("正在开发中~");
    }

    private void pushActivityToStack() {
        ActivityManager.getInstance().pushActivity(this);
    }

    public void finish() {
        super.finish();
        ActivityManager.getInstance().removeActivity(this);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (event.getAction() == KeyEvent.ACTION_UP) {
                    ActivityManager.getInstance().popActivity();
                    return false;
                }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void setFirstTag(Object tag) {
        toolbar.setTag(R.id.tag_key_1, tag);
    }

    public void setSecondTag(Object tag) {
        toolbar.setTag(R.id.tag_key_2, tag);
    }

    public Object getFirstTag() {
        return toolbar.getTag(R.id.tag_key_1);
    }

    public Object getSecondTag() {
        return toolbar.getTag(R.id.tag_key_2);
    }
}
